<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives, reactive, computed, getCurrentInstance } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, 
  NSelect, 
  NFlex, 
  useMessage,
  NDatePicker,
  NInputNumber
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
import { exportToExcel } from '@/utils/exportUtils'

defineOptions({ name: '客户消费排行榜' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  search_loading: false,
  total_customers: 0,
  total_amount: 0,
  api_total: 0  // 存储接口返回的总数
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '客户消费排行榜',
  initForm: {},
  doCreate: () => Promise.resolve(),
  doUpdate: () => Promise.resolve(),
  doDelete: () => Promise.resolve(),
  refresh: () => $table.value?.handlerefresh(),
})

onMounted(() => {
  $table.value?.handleSearch()
  fetchTotal()
})

// 获取总数
const fetchTotal = async () => {
  try {
    const response = await api.get_customer_rank({
      ...queryItems.value,
      page_size: 1, // 只获取一页数据
    })
    if (response.data && response.total) {
      data.api_total = response.total
    }
  } catch (error) {
    console.error('获取总数失败:', error)
  }
}

// 导出功能
const handleExport = async () => {
  try {
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    const { data: tableData } = await api.get_customer_rank({
      ...queryItems.value,
      is_export: 1,
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    const exportData = tableData.map((item, index) => ({
      排名: index + 1,
      客户姓名: item.name,
      手机号: item.mobile,
      病历号: item.card_number,
      推荐人: item.parent_name,
      生日: item.bi_date,
      渠道来源: item.hkqd,
      所属顾问: item.butler_name,
      消费总额: item.total_price,
      '套餐/项目总数': item.total_project_count,
      地址: item.address
    }))

    exportToExcel(exportData, `客户消费排行榜_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

// 表格列定义
const columns = [
  {
    title: '排名',
    key: 'rank',
    width: 80,
    align: 'center',
    render: (row, index) => {
      const rank = index + 1
      let rankStyle = {}
      if (rank === 1) {
        rankStyle = { background: 'linear-gradient(135deg, #ffd700, #ffed4e)', color: '#333', fontWeight: 'bold' }
      } else if (rank === 2) {
        rankStyle = { background: 'linear-gradient(135deg, #c0c0c0, #e8e8e8)', color: '#333', fontWeight: 'bold' }
      } else if (rank === 3) {
        rankStyle = { background: 'linear-gradient(135deg, #cd7f32, #daa520)', color: 'white', fontWeight: 'bold' }
      }
      
      return h('div', { 
        style: { 
          padding: '4px 8px', 
          borderRadius: '4px',
          textAlign: 'center',
          ...rankStyle
        } 
      }, rank)
    }
  },
  {
    title: '客户信息',
    key: 'customer_info',
    width: 150,
    align: 'center',
    fixed: 'left',
    render: (row) => {
      return h(NFlex, { justify: "center", align: "center" }, [
        row.photo ? 
          h(NImage, {
            width: 32,
            height: 32,
            src: row.photo,
            style: 'border-radius: 50%; margin-right: 8px; object-fit: cover;',
            fallbackSrc: '/src/assets/images/mz.jpg'
          }) :
          h(NAvatar, { 
            size: 32, 
            round: true,
            style: 'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-weight: bold; margin-right: 8px;'
          }, () => row.name?.charAt(0) || '客'),
        h('div', { style: 'font-weight: 500; color: #333; font-size: 14px;' }, row.name || '未知客户')
      ])
    }
  },
  {
    title: '手机号',
    key: 'mobile',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
    render: (row) => {
      return row.mobile ? h(NTag, { type: 'default', size: 'small' }, () => row.mobile) : '无'
    }
  },
  {
    title: '病历号',
    key: 'card_number',
    width: 120,
    align: 'center',
    render: (row) => {
      return row.card_number ? h(NTag, { type: 'info', size: 'small' }, () => row.card_number) : '无'
    }
  },
  {
    title: '推荐人',
    key: 'parent_name',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
    render: (row) => row.parent_name || '无'
  },
  {
    title: '生日',
    key: 'bi_date',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
    render: (row) => row.bi_date || '无'
  },
  {
    title: '渠道来源',
    key: 'hkqd',
    width: 100,
    align: 'center',
    ellipsis: { tooltip: true },
    render: (row) => row.hkqd || '无'
  },
  {
    title: '所属顾问',
    key: 'butler_name',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
    render: (row) => row.butler_name || '无'
  },
  {
    title: '消费总额',
    key: 'total_price',
    width: 120,
    align: 'center',
    render: (row) => {
      return h(NTag, { 
        type: 'success', 
        size: 'small',
        style: 'font-weight: bold; font-size: 14px;'
      }, () => `¥${row.total_price?.toFixed(2) || '0.00'}`)
    }
  },
  {
    title: '套餐/项目总数',
    key: 'total_project_count',
    width: 100,
    align: 'center',
    render: (row) => {
      return h(NTag, { type: 'warning', size: 'small' }, () => `${row.total_project_count || 0}次`)
    }
  },
  {
    title: '地址',
    key: 'address',
    width: 200,
    align: 'center',
    ellipsis: { tooltip: true },
    render: (row) => row.address || '无'
  }
]

// 时间范围处理
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  if (value && value.length === 2) {
    queryItems.value.start_time = formatTimestamp(value[0])
    queryItems.value.end_time = formatTimestamp(value[1])
  } else {
    queryItems.value.start_time = null
    queryItems.value.end_time = null
  }
}

// 格式化时间戳
function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1)
  const day = pad(date.getDate())
  return `${year}-${month}-${day}`
}

// 计算总数据
const total_customers = computed(() => {
  return data.api_total
})

const total_amount = computed(() => {
  const tableData = $table.value?.tableData || []
  return tableData.reduce((sum, item) => sum + (Number(item.total_price) || 0), 0).toFixed(2)
})
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer :title="nameFromInstance+'列表'">
        <template #action>
          <NButton type="info" @click="handleExport">
            <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.get_customer_rank"
          :scroll-x="2000"
          :maxheight="420"
        >
          <template #queryBar>
            <QueryBarItem label="客户姓名" :label-width="80">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="输入客户姓名"
                @keypress.enter="$table.value?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="手机号" :label-width="80">
              <NInput
                v-model:value="queryItems.mobile"
                clearable
                type="text"
                placeholder="输入手机号"
                @keypress.enter="$table.value?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="病历号" :label-width="80">
              <NInput
                v-model:value="queryItems.card_number"
                clearable
                type="text"
                placeholder="输入病历号"
                @keypress.enter="$table.value?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="所属顾问" :label-width="80">
              <NInput
                v-model:value="queryItems.butler_name"
                clearable
                type="text"
                placeholder="输入所属顾问"
                @keypress.enter="$table.value?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="消费时间" :label-width="80">
              <NDatePicker
                v-model:value="datetimeRange"
                type="daterange"
                clearable
                placeholder="请选择时间范围"
                @update:value="handleDateRangeChange"
              />
            </QueryBarItem>
            <QueryBarItem style="line-height: 35px;color: #1890ff" label="客户总数:" :label-width="80">
              {{total_customers}}人
            </QueryBarItem>
            <QueryBarItem style="line-height: 35px;color: #52c41a" label="消费总额:" :label-width="80">
              ¥{{total_amount}}
            </QueryBarItem>
          </template>
        </CrudTable>
      </CommonPage>
    </NLayoutContent>
  </NLayout>
</template>

<style scoped>
/* 表格样式优化 */
:deep(.n-table-thead) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.n-table-thead .n-table-th) {
  color: white;
  font-weight: 600;
  border: none;
}

:deep(.n-table-tbody .n-table-tr:hover) {
  background: #f8f9ff;
}

:deep(.n-table-tbody .n-table-td) {
  border-bottom: 1px solid #f0f0f0;
}

/* 排名样式 */
:deep(.n-table-tbody .n-table-tr:nth-child(1) .n-table-td:first-child) {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #333;
  font-weight: bold;
}

:deep(.n-table-tbody .n-table-tr:nth-child(2) .n-table-td:first-child) {
  background: linear-gradient(135deg, #c0c0c0, #e8e8e8);
  color: #333;
  font-weight: bold;
}

:deep(.n-table-tbody .n-table-tr:nth-child(3) .n-table-td:first-child) {
  background: linear-gradient(135deg, #cd7f32, #daa520);
  color: white;
  font-weight: bold;
}
</style>